package com.ddc.study.feature.main.tree;

import android.view.View;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.ddc.study.R;
import com.ddc.study.base.TabReselectFragment;
import com.ddc.study.entity.Tree;
import com.ddc.study.feature.main.tree.detail.TreeDetailActivity;
import com.ddc.study.util.Log;
import com.google.android.material.chip.Chip;
import com.google.android.material.chip.ChipGroup;

import java.lang.reflect.Field;
import java.util.List;

import androidx.annotation.LayoutRes;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;
import butterknife.BindView;
import butterknife.OnClick;

/**
 * Created on 2018/5/22.
 *
 * @author lshun
 * @version 1.0
 */
public class TreeFragment extends TabReselectFragment<TreeContract.IView, TreeContract.IPresenter>
        implements TreeContract.IView {
    @Override
    protected int getLayoutRes() {
        return R.layout.frag_tree;
    }

    @BindView(R.id.swipe_refresh_layout)
    SwipeRefreshLayout mSwipeRefreshLayout;

    @BindView(R.id.recycler_view_title)
    RecyclerView mRecyclerView;

    @BindView(R.id.group_chip)
    ChipGroup mChipGroup;

    @BindView(R.id.layout_load_failed)
    View mLoadFailedView;

    private Adapter mAdapter;

    private List<Tree> mData;

    @Override
    protected void initView() {
        super.initView();
        if (getActivity() == null) return;

        mSwipeRefreshLayout.setOnRefreshListener(() -> mPresenter.loadTreeData());

        mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));

        if (mAdapter == null) {
            mAdapter = new Adapter(R.layout.item_navigation_title);
            mPresenter.loadTreeData();

            mAdapter.setOnItemClickListener((adapter, view, position) -> {
                Tree item = mAdapter.getItem(position);
                if (item == null) return;
                mAdapter.setPosition(position);

                mChipGroup.removeAllViews();
                Chip chip;
                for (final Tree tree : item.getChildren()) {
                    chip = (Chip) View.inflate(getActivity(), R.layout.layout_chip, null);
                    chip.setText(tree.getName());
                    chip.setOnClickListener(v -> TreeDetailActivity.openDetail(getActivity(), tree.getId(), tree.getName()));
                    mChipGroup.addView(chip);
                }
            });
            mAdapter.bindToRecyclerView(mRecyclerView);
        } else {
            //视图销毁重建  由于adapter不能被多次绑定 所以先用反射清空绑定值
            try {
                Field f = mAdapter.getClass().getSuperclass().getDeclaredField("mRecyclerView");
                f.setAccessible(true);
                f.set(mAdapter, null);
            } catch (NoSuchFieldException | IllegalAccessException e) {
                e.printStackTrace();
            }
            mAdapter.bindToRecyclerView(mRecyclerView);
            //在销毁重建后需要通知更新视图
            mAdapter.notifyDataSetChanged();

            //ChipGroup中的内容是动态添加的   在Fragment视图销毁重建后需要手动还原其内容
            if (mData != null && mData.size() > mAdapter.mPosition) {
                mChipGroup.removeAllViews();
                Tree item = mData.get(mAdapter.mPosition);
                Chip chip;
                for (final Tree tree : item.getChildren()) {
                    chip = (Chip) View.inflate(getActivity(), R.layout.layout_chip, null);
                    chip.setText(tree.getName());
                    chip.setOnClickListener(v -> TreeDetailActivity.openDetail(getActivity(), tree.getId(), tree.getName()));
                    mChipGroup.addView(chip);
                }
            }
        }

        setRetainInstance(true);
    }

    @Override
    protected TreeContract.IPresenter createPresenter() {
        return new TreePresenter();
    }

    @Override
    public void showTreeData(@Nullable List<Tree> data) {
        mData = data;
        if (data == null || data.isEmpty()) {//加载失败
            //如果没有数据就显示加载失败视图
            if (mAdapter.getData().isEmpty()) {
                mLoadFailedView.setVisibility(View.VISIBLE);
                mSwipeRefreshLayout.setVisibility(View.GONE);
            } else {
                showToast(R.string.refresh_failed);
            }
        } else {
            mAdapter.setNewData(data);

            //TODO 修改为 -> 如果列表中当前选中的item变化了就选中第一项并滚动到当前位置
            //更新当前选中项的内容
            mAdapter.setOnItemClick(null, mAdapter.mPosition);
        }
        if (mSwipeRefreshLayout.isRefreshing())
            mSwipeRefreshLayout.setRefreshing(false);
    }

    @OnClick(R.id.layout_load_failed)
    void loadData() {
        Log.e(TAG, "loadData -> ");
        mPresenter.loadTreeData();
        showLoadingView();
    }

    @Override
    public void onTabReselect() {
        //当前是停在最顶端直接设置第一项选中
        if (mRecyclerView.canScrollVertically(-1)) {
            mRecyclerView.smoothScrollToPosition(0);
            //在滑动到顶部后再选中第一条数据
            mRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
                @Override
                public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) {
                    super.onScrollStateChanged(recyclerView, newState);
                    //必须等到滑动停止才处理
                    if (newState != RecyclerView.SCROLL_STATE_IDLE) return;
                    //移除这个临时的监听器以免影响其他操作
                    mRecyclerView.removeOnScrollListener(this);
                    //如果还能往上滑动  说明不在停在顶端  直接返回不处理
                    if (mRecyclerView.canScrollVertically(-1)) return;
                    //停到了顶端 选中第一项   【Note：参数view是直接传入的null】
                    mAdapter.getOnItemClickListener()
                            .onItemClick(mAdapter, null, 0);
                }
            });
        } else {
            mAdapter.getOnItemClickListener().onItemClick(mAdapter, null, 0);
        }
    }

    private void showNormalView() {
        mLoadFailedView.setVisibility(View.GONE);
        mSwipeRefreshLayout.setVisibility(View.VISIBLE);
        if (mSwipeRefreshLayout.isRefreshing()) {
            mSwipeRefreshLayout.setRefreshing(false);
        }
    }

    private void showLoadingView() {
        mLoadFailedView.setVisibility(View.GONE);
        mSwipeRefreshLayout.setVisibility(View.VISIBLE);
        if (!mSwipeRefreshLayout.isRefreshing()) {
            mSwipeRefreshLayout.setRefreshing(true);
        }
    }

    private void showLoadFailedView() {
        mSwipeRefreshLayout.setVisibility(View.GONE);
        mLoadFailedView.setVisibility(View.VISIBLE);
        if (mSwipeRefreshLayout.isRefreshing()) {
            mSwipeRefreshLayout.setRefreshing(false);
        }
    }

    public static final class Adapter extends BaseQuickAdapter<Tree, BaseViewHolder> {
        private int mPosition;//选中的index

        public Adapter(@LayoutRes int layoutResId) {
            super(layoutResId);
        }

        public void setPosition(int position) {
            if (mPosition == position) return;
            int oldPosition = mPosition;
            mPosition = position;
            notifyItemChanged(oldPosition);
            notifyItemChanged(mPosition);
        }

        @Override
        protected void convert(BaseViewHolder helper, Tree item) {
            TextView tv = helper.getView(R.id.tv_content);
            tv.setSelected(helper.getAdapterPosition() == mPosition);
            tv.setText(item.getName());
        }
    }
}
